﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Xml;

namespace AIC_PN
{
    public partial class BaoCaoSo16_Update : MyFromBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (!IsPostBack)
            {
                BindDataToControls();
            }
        }

        /// <summary>
        /// Thủ tục kiểm tra quyền sử dụng của người dùng có được quyền truy cập vào mục này hay không?
        /// </summary>
        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("BaoCaoMau16");
            if (Role == null || Role["Xem"] == 0 || ((Role["Xem"] == 1 && Role["Sua"] == 0)))
            {
                Response.Redirect("Index.aspx?p=0");
            }
        }

        /// <summary>
        /// Bind Data vào các contrls như Combobox, ListBox, textBox ...
        /// </summary>
        private void BindDataToControls()
        {
            //TODO
            if (Session["userid"] != null)
            {

                string sql = "Select DV.* " +
                             "From tblDonVi DV " +
                             "Inner Join tblUser U On U.DonViID=DV.ID " +
                             "Where U.ID=" + Session["userid"];
                DataTable dtDV = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                tdTenDonVi.InnerText = "(" + dtDV.Rows[0]["MaDV"] + ") " + dtDV.Rows[0]["TenDV"];

                sql = "Select ID,TenDM From tblDanhMuc Where MaDM='" + MyConst.DanhMuc.KyBaoCao.Ma + "' ";
                SqlDataReader reKyBaoCao = SqlHelper.ExecuteReader(CommandType.Text, sql);
                clsDataBind.CreateCombo("Tất cả", reKyBaoCao, cboKyBaoCao, 1, 0);
            }
        }

        /// <summary>
        /// Bind Data vào gridview
        /// </summary>
        private void BindDataToGrid()
        {
            List<SqlParameter> lstParams = new List<SqlParameter>();
            lstParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
            lstParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
            lstParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text,
                "SELECT BC.*,TenDV FROM dbo.tblBaoCaoMau16 BC INNER JOIN dbo.tblDonVi DV ON DV.ID = BC.F1 " +
                "WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID", lstParams);
            grvData.DataSource = dt;
            grvData.DataBind();
            //btnLuu.Visible = true;
            grvData.Visible = true;
        }

        #region Events

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("Index.aspx");
        }

        protected void cboKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboKyBaoCao.SelectedIndex > 0)
            {
                //btnLuu.Visible = false;
                grvData.Visible = false;
                grvData.EditIndex = -1;
                BindDataToGrid();
                if (((DataTable)grvData.DataSource).Rows.Count == 0)
                {
                    SqlTransaction MyTran = SqlHelper.BeginTransaction();
                    try
                    {
                        List<SqlParameter> lstParams = new List<SqlParameter>();
                        lstParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
                        lstParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
                        lstParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
                        string sql = "INSERT INTO tblBaoCaoMau16(KyBaoCaoID_DM,DonViID,F1,F2,F3,F4,F5,F6,F7,F8,F9,IsCommon,CreateDate,UpdateDate,UserID) " +
                                     "(SELECT @KyBaoCaoID_DM,@DonViID,DV.ID,0,0,0,0,0,0,0,0,0,GETDATE(),GETDATE(),@UserID FROM dbo.tblDonVi DV WHERE DV.ID != DV.FatherID)";
                        SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql, lstParams);
                        sql = "INSERT INTO tblBaoCaoMau16(KyBaoCaoID_DM,DonViID,IsCommon,CreateDate,UpdateDate,UserID) VALUES (@KyBaoCaoID_DM,@DonViID,1,GETDATE(),GETDATE(),@UserID)";
                        SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql, lstParams);
                        MyTran.Commit();
                    }
                    catch
                    {
                        MyTran.Rollback();
                    }
                    grvData.EditIndex = -1;
                    BindDataToGrid();
                }
                else
                {
                    //BindDataToTextField();
                }
            }
            else
            {
                //btnLuu.Visible = false;
                grvData.Visible = false;
            }
        }

        /*private void BindDataToTextField()
        {
            List<SqlParameter> lstParams = new List<SqlParameter>();
            string sql = "SELECT * FROM dbo.tblBaoCaoMau16 WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID AND IsCommon = 1";
            lstParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
            lstParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParams);
            if (dt.Rows.Count > 0)
            {
                txtNgayBaoCao.Text = dt.Rows[0]["CM_ThoiGianBaoCao"].ToString();
                txtGhiChu.Text = dt.Rows[0]["CM_NoiDung"].ToString();
            }

        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {

            string sSQL = "Update tblBaoCaoMau16 Set CM_ThoiGianBaoCao = @CM_ThoiGianBaoCao,CM_NoiDung = @CM_NoiDung " +
                           "Where IsCommon=1 And DonViID=" + MyCommon.GetDonViID(Session["userid"].ToString()) + " And KyBaoCaoID_DM=" + cboKyBaoCao.SelectedValue;
            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@CM_ThoiGianBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtNgayBaoCao.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@CM_NoiDung", SqlDbType.NVarChar, ParameterDirection.Input, txtGhiChu.Text.Trim()));
            int result = SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);
            if (result > 0)
            {
                MyCommon.AddMessage(this.Master, "Cập nhật báo cáo thành công !", MyConst.MessageType.Success);
            }
            else
            {
                MyCommon.AddMessage(this.Master, "Cập nhật báo cáo lỗi !", MyConst.MessageType.Error);
            }
        }*/

        #endregion Events


        #region GridCommand

        private static void AddMergedCells(GridViewRow objgridviewrow, TableCell objtablecell, int colspan, int rowspan, string celltext)
        {
            objtablecell = new TableCell();
            objtablecell.Text = celltext;
            objtablecell.ColumnSpan = colspan;
            objtablecell.RowSpan = rowspan;
            objtablecell.HorizontalAlign = HorizontalAlign.Center;
            objgridviewrow.Cells.Add(objtablecell);
        }

        protected void grvData_RowCreated(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.Header)
            {

                GridView objGridView = (GridView)sender;
                //GridViewRow objgridviewrow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);

                GridViewRow objgridviewrow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);
                GridViewRow objgridviewrow2 = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);

                TableHeaderCell objtablecell = new TableHeaderCell();
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "TT");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Đơn vị");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Tổng số hội viên");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Số hội viên tham gia tiết kiệm");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Số hội viên được vay vốn từ hoạt động tiết kiệm");
                AddMergedCells(objgridviewrow, objtablecell, 3, 1, "Các loại hình tiết kiệm (SL)");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Mức tiết kiệm thấp nhất (số tiền/01 người)");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Số tiền tiết kiệm năm " + DateTime.Now.Year);
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Sửa");
                objgridviewrow.BackColor = System.Drawing.ColorTranslator.FromHtml("#109AEA");
                objgridviewrow.Font.Bold = true;
                objgridviewrow.ForeColor = System.Drawing.Color.White;
                objGridView.Controls[0].Controls.AddAt(0, objgridviewrow);

                objtablecell = new TableHeaderCell();
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tiết kiệm tại các hội PN");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tiết kiệm qua các tôt Phụ nữ tiết kiệm");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tiết kiệm trong các tổ góp vốn quay vòng");
                objgridviewrow2.BackColor = System.Drawing.ColorTranslator.FromHtml("#109AEA");
                objgridviewrow2.Font.Bold = true;
                objgridviewrow2.ForeColor = System.Drawing.Color.White;
                objGridView.Controls[0].Controls.AddAt(1, objgridviewrow2);
            }
        }

        protected void grvData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            RowDataBound(sender, e);
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string sID = e.CommandArgument.ToString().Trim();
            string sCommandName = e.CommandName;

            if ((sCommandName == AIC_PN.MyConst.Action.Approve))
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                for (int i = 2; i <= 9; i++)
                {
                    TextBox txtField = (TextBox)grvData.Rows[grvData.EditIndex].Cells[i].Controls[0];
                    arrParams.Add(SqlHelper.CreateParameterObject("F" + i, SqlDbType.Float, ParameterDirection.Input, txtField.Text));
                }
                string sql = "UPDATE dbo.tblBaoCaoMau16 SET F2 = @F2,F3 = @F3,F4 = @F4,F5 = @F5,F6 = @F6,F7 = @F7,F8 = @F8,F9 = @F9,UpdateDate = GETDATE(),UserID = @UserID WHERE ID = @ID";
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
                arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(sID)));
                int result = SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                if (result > 0)
                {
                    MyCommon.AddMessage(this.Master, "Cập nhật báo cáo thành công !", MyConst.MessageType.Success);
                }
                else
                {
                    MyCommon.AddMessage(this.Master, "Cập nhật báo cáo lỗi !", MyConst.MessageType.Error);
                }
                // cap nhat vao database
                grvData.EditIndex = -1;
                BindDataToGrid();
            }
        }

        protected void grvData_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvData.EditIndex = e.NewEditIndex;
            BindDataToGrid();
        }



        protected void grvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //grvData.PageIndex = e.NewPageIndex;
            //BindDataToGrid();
        }


        protected void grvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvData.EditIndex = -1;
            BindDataToGrid();
        }
        #endregion GridCommand
    }
}
